<template>
  <div class="essay" id="myElement" :style="`width:${titleWidth + width}px;`">
    <div class="item" v-if="show">
      <!-- 标题 -->
      <div class="titleWidth" :style="`width:${titleWidth}px;min-height:${itemHeight}px`">{{ list.name ? list.name : ''
      }}
      </div>
      <!-- 右侧进度条盒子 -->
      <div class="item-right" :style="`min-height:${itemHeight}px;width:${width}px;`"
        @contextmenu.prevent="onContextmenu($event)">

        <!-- 单条进度条 -->
        <!-- :style="{ Zindex: list.length - cidx }" -->
        <div v-for="(child, cidx) in list.injectionList" :key="cidx" class="item-for">
          <!-- 持续 -->
          <div v-if="child.mode == '持续'" class="line"
            :style="`width:${child.width}px;marginLeft: ${child.left}px;background-color:${`#5ac725`};`"
            @mousedown.stop="child.rateList && child.rateList.length ? '' : mousedown($event, cidx)">
            <!-- 标题 -->
            <i class="child-name" :style="`color:${child.color};`"> {{ child.name }}</i>
            <!-- 左拖动按钮 -->
            <i class="el-icon-caret-left line-left-drag" :style="`color:${child.color};`"
              @mousedown.stop="leftMouse($event, cidx)" v-if="child.left >= 0"></i>
            <!-- 又拖动按钮 -->
            <i class="el-icon-caret-right  line-right-drag" :style="`color:${child.color};`"
              @mousedown.stop="rightMouse($event, cidx)" v-if="(child.left + child.width) <= width"></i>
            <!-- 中间的点位 -->
            <span class="line-center-drag" :style="`marginLeft:${oneItem.left - child.left}px;`"
              v-for="(oneItem, oneIndex) in child.rateList" :key="oneIndex"
              @mousedown.stop="centerMouse($event, cidx, oneIndex)">
              <i class="el-icon-top" :style="`color: #e04040;`"></i>
            </span>
          </div>

          <!-- 单次 -->
          <div v-if="child.mode == '单次'" class="line" :style="`marginLeft: ${child.left}px;`"
            @mousedown.stop="mousedownOnce($event, cidx)">
            <!-- 图标 -->
            <i class="el-icon-caret-top line-once-drag" :style="`color:${child.color};`" v-if="child.left >= 0"></i>
            <!-- 标题 -->
            <i class="child-name-once" :style="`color:${child.color};`"> {{ child.name }}</i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

export default {
  props: {
    childClIdx: {//当前列表的下标
      type: Array,
      default: null,//px
    },
    titleWidth: {//标题宽度
      type: Number,
      default: 100,//px
    },
    width: {//右侧宽度
      type: Number,
      default: 600,//px
    },
    height: {//盒子高度
      type: Number,
      default: 600,//px
    },
    //  单个列表的高度
    itemHeight: {
      type: Number,
      default: 60,//px
    },
    hour: {
      type: Number,
      default: 5,
    },
    // 起始时间
    createTime: {
      type: String,
      default: '2023-04-08 11:10:05',//px
    },
    // 数据
    list: {
      type: Object,
      default: {},//px
    },
  },
  watch: {
    hour() {
      this.$nextTick(() => {
        this.init()
      })
    },
    createTime() {
      this.$nextTick(() => {
        this.init()
      })
    },
  },
  data() {
    return {
      activeChild: 0,//操作项
      show: false,
      createTimeMS: 0,//起始时间毫秒数
      color: ['#3c9cff', '#f9ae3d', '#1010FF', '#f56c6c', '#909399']
    }
  },
  mounted() {
    // 监听关闭事件
    document.onmouseup = () => {
      this.offMouse()
    }
    document.addEventListener('visibilitychange', () => {
      let isHidden = document.hidden;
      if (isHidden) {
        //'隐藏';
        this.offMouse()
      } else {
        //'显示'
        this.offMouse()
      }
    });
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    // 初始化数据
    async init() {
      this.show = false
      // 时间转为毫秒数
      this.createTimeMS = Date.parse(this.createTime)
      if (this.list.injectionList) {
        this.list.injectionList.forEach((ele, i) => {
          // 时间转为帧率
          this.timeHz(i)
          // 设置颜色
          if (!ele.color) {
            ele.color = this.color[i]
          }
        })
      } else {
        this.list.injectionList = []
      }
      // console.log(this.list);
      //排序
      this.listSort()
      this.show = true
      // 更新数据
      if (this.childClIdx) {
        this.$emit('updateDataList', this.childClIdx, this.list)
      }
      // 关闭弹窗并且从新排序
      this.$emit('stopTip')
    },
    offMouse() {
      this.listSort()
      document.onmousemove = null; //停止监听鼠标事件
      // 关闭弹窗
      this.$emit('stopTip')
      this.$forceUpdate();
    },
    // 拖动左侧箭头
    leftMouse(event, cidx) {
      document.onmouseup = () => {
        this.offMouse()
      }
      this.activeChild = cidx
      // 获取按下时鼠标初始位置
      let X = event.pageX;
      // 获取初始left
      let oldLeft = this.list.injectionList[cidx].left
      let oldWidth = this.list.injectionList[cidx].width
      // 获取子项里，面最小的值
      let maxLeft = null
      if (this.list.injectionList[cidx].rateList && this.list.injectionList[cidx].rateList.length) {
        maxLeft = Math.min.apply(Math, this.list.injectionList[cidx].rateList.map(item => { return item.left })) //- this.list.injectionList[cidx].left
      }
      // 拖动需要写到down里面
      document.onmousemove = (event) => {
        // 获取移动的距离
        let diff = event.pageX - X;
        // console.log(diff);
        // 计算当前进度条的left
        let newLeft = oldLeft + diff;
        // 控制最大左侧等于 旧的左+旧的宽
        if (newLeft >= oldLeft + oldWidth) {
          newLeft = oldLeft + oldWidth
        }
        //控制最大不能大于子项里面的最小值   
        if (maxLeft && newLeft > maxLeft) {
          newLeft = maxLeft
          this.list.injectionList[cidx].left = newLeft;
          return
        }
        this.list.injectionList[cidx].left = newLeft;
        // // // 设置左边距
        let newWidth = oldWidth - diff
        if (newWidth < 0) {
          newWidth = 0
        }
        this.list.injectionList[cidx].width = newWidth;
        // 控制滚动条
        // 设置时间
        this.setTimes(cidx)
        // 控制弹窗
        this.tipMove(event.clientX, event.clientY)
        this.$forceUpdate();
      }
    },
    // 拖动右侧箭头
    rightMouse(event, cidx) {
      document.onmouseup = () => {
        this.offMouse()
      }
      this.activeChild = cidx
      let X = event.pageX
      let oldWidth = this.list.injectionList[cidx].width - X
      let oldLeft = this.list.injectionList[cidx].left
      // 最小宽度  子项里面的最大宽度
      let maxWidth = null
      if (this.list.injectionList[cidx].rateList && this.list.injectionList[cidx].rateList.length) {
        maxWidth = Math.max.apply(Math, this.list.injectionList[cidx].rateList.map(item => { return item.left })) - this.list.injectionList[cidx].left
      }
      document.onmousemove = (event) => {
        // 获取移动的距离
        let diff = event.pageX;
        // 计算当前进度条的left
        let moveWidth = oldWidth + diff;
        // 控制最小宽等于 左侧
        if (moveWidth <= 0) {
          moveWidth = 0
        }
        // 控制最大宽度 不能小于 左侧宽度 + 子项最大值left
        if (maxWidth && moveWidth <= maxWidth) {
          moveWidth = maxWidth
        }
        this.list.injectionList[cidx].width = moveWidth;
        // 设置时间
        this.setTimes(cidx)
        // 控制弹窗
        this.tipMove(event.clientX, event.clientY)
        this.$forceUpdate();
      }
    },
    // 拖动进度条
    mousedown(event, cidx) {
      document.onmouseup = () => {
        this.offMouse()
      }
      this.activeChild = cidx
      // 获取按下时鼠标初始位置
      let X = event.pageX;
      // 获取初始left
      let voiceProLen = this.list.injectionList[cidx].left
      // 拖动需要写到down里面
      document.onmousemove = (event) => {
        // 获取移动的距离
        let diff = event.pageX - X;
        // 计算当前进度条的left
        let voiceProLenNew = voiceProLen + diff;
        // 赋值
        this.list.injectionList[cidx].left = voiceProLenNew;
        // 设置时间
        this.setTimes(cidx)
        // 控制弹窗
        this.tipMove(event.clientX, event.clientY)
        this.$forceUpdate();
      }
    },
    // 拖动多次中间子项目
    centerMouse(event, cidx, oneIndex) {
      document.onmouseup = () => {
        this.offMouse()
      }
      this.activeChild = cidx
      // 获取按下时鼠标初始位置
      let X = event.pageX;
      // 获取初始left
      let voiceProLen = this.list.injectionList[cidx].rateList[oneIndex].left
      // 获取子项里，面最小的值
      let minLeft = this.list.injectionList[cidx].left
      // 最大右侧
      let maxWidth = this.list.injectionList[cidx].left + this.list.injectionList[cidx].width
      // 拖动需要写到down里面
      document.onmousemove = (event) => {
        // 获取移动的距离
        let diff = event.pageX - X;
        // 计算当前进度条的left
        let voiceProLenNew = voiceProLen + diff;
        // 超过左侧 控制
        if (voiceProLenNew < minLeft) {
          voiceProLenNew = minLeft
        }
        // 草果右侧最大值 控制
        if (voiceProLenNew > maxWidth) {
          voiceProLenNew = maxWidth
        }
        // 赋值
        this.list.injectionList[cidx].rateList[oneIndex].left = voiceProLenNew;
        // 设置时间
        let time = Number(this.hour) * 60 * 60 * 1000  // 小时转为毫秒
        let startTime = this.formatSeconds((time / this.width) * this.list.injectionList[cidx].rateList[oneIndex].left, '1')
        this.list.injectionList[cidx].rateList[oneIndex].startTime = startTime
        // 控制弹窗
        this.$emit('setTip', {
          x: event.clientX,
          y: event.clientY,
          startTime: this.list.injectionList[cidx].rateList[oneIndex].startTime,
        })
        // 更新数据
        this.$emit('updateDataList', this.childClIdx, this.list)
        this.$forceUpdate();
      }
    },
    // 拖动单次进度条
    mousedownOnce(event, cidx) {
      document.onmouseup = () => {
        this.offMouse()
      }
      this.activeChild = cidx
      // 获取按下时鼠标初始位置
      let X = event.pageX;
      // 获取初始left
      let voiceProLen = this.list.injectionList[cidx].left
      // 拖动需要写到down里面
      document.onmousemove = (event) => {
        // 获取移动的距离
        let diff = event.pageX - X;
        // 计算当前进度条的left
        let voiceProLenNew = voiceProLen + diff;
        // 赋值
        this.list.injectionList[cidx].left = voiceProLenNew;
        // 设置时间
        this.setTimes(cidx)
        this.tipMove(event.clientX, event.clientY)
        this.$forceUpdate();
      }
    },
    timeHz(cindex) {
      let ruleHz = (this.hour * 60 * 60 * 1000) / this.width//每帧的毫秒数
      if (this.list.injectionList[cindex].mode == '持续') {
        // 左侧
        let left = Date.parse(this.list.injectionList[cindex].startTime)//左侧时间戳
        let width = Date.parse(this.list.injectionList[cindex].endTime)//宽度时间戳
        let leftDiff = (left - this.createTimeMS) / ruleHz//左侧移动的距离
        let widthDiff = ((width - this.createTimeMS) - (left - this.createTimeMS)) / ruleHz // 右侧移动的距离
        this.list.injectionList[cindex].left = leftDiff
        this.list.injectionList[cindex].width = widthDiff
        // 配置其中单个的数量
        if (this.list.injectionList[cindex].rateList && this.list.injectionList[cindex].rateList.length) {
          this.list.injectionList[cindex].rateList.forEach(v => {
            // console.log(v);
            if (v.startTime) {
              let left = Date.parse(v.startTime)//左侧时间戳
              let leftDiff = (left - this.createTimeMS) / ruleHz//左侧移动的距离
              v.left = leftDiff
            }
          })
          console.log(this.list.injectionList[cindex]);
        }
      }
      if (this.list.injectionList[cindex].mode == '单次') {
        let left = Date.parse(this.list.injectionList[cindex].startTime)//左侧时间戳
        let leftDiff = (left - this.createTimeMS) / ruleHz//左侧移动的距离
        this.list.injectionList[cindex].left = leftDiff
      }
      // let testTime = Date.parse(time)  //传入的时间
      // let clTime = testTime - this.createTimeMS //相差的时间
      // return (clTime / ruleHz)//left
    },
    // 设置时间
    setTimes(cidx) {
      // 持续
      if (this.list.injectionList[cidx].mode == '持续') {
        // 开始时间 
        let time = Number(this.hour) * 60 * 60 * 1000  // 小时转为毫秒
        let startTime = this.formatSeconds((time / this.width) * this.list.injectionList[cidx].left, '1')
        let endTime = this.formatSeconds((time / this.width) * (this.list.injectionList[cidx].left + this.list.injectionList[cidx].width), '1')
        this.list.injectionList[cidx].startTime = startTime
        this.list.injectionList[cidx].endTime = endTime
      }
      // 单次
      if (this.list.injectionList[cidx].mode == '单次') {
        let time = Number(this.hour) * 60 * 60 * 1000  // 小时转为毫秒
        let startTime = this.formatSeconds((time / this.width) * this.list.injectionList[cidx].left, '1')
        this.list.injectionList[cidx].startTime = startTime
      }
      // 更新数据
      if (this.childClIdx) {
        this.$emit('updateDataList', this.childClIdx, this.list)
      }
    },
    // 毫秒转换为时分秒
    formatSeconds(num, type) {
      function setDb(num) {
        //补零操作
        if (num < 10) {
          return '0' + num;
        } else {
          return '' + num;
        }
      }
      let time = new Date(this.createTimeMS + num);
      let year = time.getFullYear();//年
      let mon = setDb(time.getMonth() + 1);//0
      let day = setDb(time.getDate());//24
      let hour = setDb(time.getHours());//时
      let min = setDb(time.getMinutes());//分
      let sec = setDb(time.getSeconds());//秒
      if (type == '1') {
        // 年月日时分秒
        return `${year}-${mon}-${day} ${hour}:${min}:${sec}`
      } else if (type == '2') {
        // 时分秒
        return `${hour}:${min}:${sec}`
      }
    },
    // 设置浮标位置
    tipMove(x, y) {
      let startTime = this.list.injectionList[this.activeChild].startTime
      let endTime = this.list.injectionList[this.activeChild].endTime
      this.$emit('setTip', {
        x,
        y,
        startTime,
        endTime
      })
    },
    // 排序
    listSort() {
      function compare1(obj1, obj2) {
        var val1 = obj1.left;
        var val2 = obj2.left;
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      }
      this.list.injectionList.sort(compare1)
    },
    // 点击右键
    onContextmenu(event) {
      let items = [
        // 名称
        { icon: 'el-icon-info', label: `${this.list.name || ''}`, disabled: true },
        // 编辑全部
        {
          label: "编辑",
          divided: true,
          icon: "el-icon-edit",
          onClick: () => {
            this.$emit('editAll', this.list)
          },
        },
        // 删除全部
        {
          label: "删除(D)",
          divided: true,
          icon: "el-icon-delete-solid"
        },
      ]
      // 循环塞入单个数据
      this.list.injectionList.forEach(ele => {
        let val = {
          label: `${ele.name || ''}`,
          divided: true,
          icon: 'el-icon-setting',
          minWidth: 0,
          // 编辑单条
          children: [{
            label: "编辑",
            icon: 'el-icon-edit',
            onClick: () => {
              console.log("编辑",);
              this.$emit('editItem', ele)
            },
          },
          // 删除单条
          {
            label: "删除",
            icon: 'el-icon-error',
            onClick: () => {
              console.log("删除", ele.name);
            }
          }]
        }
        items.push(val)
      })
      this.$contextmenu({
        items,
        event, // 鼠标事件信息
        customClass: "custom-class", // 自定义菜单 class
        zIndex: 3, // 菜单样式 z-index
        minWidth: 230 // 主菜单最小宽度
      });
      return false;
    },
  }
}
</script>
<style lang="scss" scoped>
.custom-class .menu_item__available:hover,
.contextmenu_menu menu custom-class {
  z-index: 9999999;
}

.custom-class .menu_item_expand {
  background: #31C2AF !important;
  color: #ff4050 !important;
}

.essay {
  //禁止滑词
  user-select: none;
  border-right: 1px solid #31C2AF;
  border-bottom: 1px solid #31C2AF;

  .item {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: left;

    .titleWidth {
      border-right: 1px solid #31C2AF;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .item-right {
      overflow: hidden;
      padding: 20px 0;
      position: relative;

      .item-for {
        position: absolute;
        left: 0;
        top: 50%;
      }

      .line {
        background-color: #31C2AF;
        height: 3px;
        position: relative;
        cursor: grab;
        margin-bottom: 10px;

        .child-name {
          font-size: 0.4em;
          opacity: 0.5;
          text-align: center;
          position: absolute;
          top: -15px;
          left: 50%;
        }

        .child-name-once {
          opacity: 0.5;
          font-size: 0.4em;
          text-align: left;
          min-width: 100px;
          position: absolute;
          top: 10px;
          left: 0px;
        }

        .line-left-drag {
          z-index: 1;
          cursor: w-resize;
          position: absolute;
          left: -4px;
          bottom: -15px;
          color: #31C2AF;
        }

        .line-once-drag {
          z-index: 1;
          cursor: pointer;
          position: absolute;
          left: -4px;
          bottom: -10px;
          color: #31C2AF;
        }

        .line-center-drag {
          z-index: 1;
          cursor: pointer;
          position: absolute;
          left: -9px;
          bottom: -2px;
          color: #31C2AF;
        }

        .line-right-drag {
          z-index: 1;
          cursor: e-resize;
          position: absolute;
          right: -4px;
          bottom: -15px;
          color: #31C2AF;
        }
      }
    }
  }
}

.tip {
  position: fixed;
  background-color: rgba(225, 225, 255, 0.9);
  padding: 5px;
  border-radius: 5px;
  z-index: 9999;
}
</style>